package com.hy.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 
 * @author yoka24443
 *
 */
public class IPFilter implements Filter {
	private String ip;
	protected FilterConfig filterConfig = null;
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig = filterConfig;
		this.ip = filterConfig.getInitParameter("ip");
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		String remoteIP = request.getRemoteAddr();
		String subRemoteIP = remoteIP.substring(0,  remoteIP.lastIndexOf('.'));
		String subIP = ip.substring(0, ip.lastIndexOf('.'));
		
		response.setCharacterEncoding("gb2312");
		if(subRemoteIP.equals(subIP)) {
			filterChain.doFilter(request, response);
		} else {
			PrintWriter out = response.getWriter();
			out.println("<font color=\"red\"><b>您的IP地址被禁止访问。</b></font>");
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
